package dingyunchi.job.controller;

import dingyunchi.job.entity.Student;
import dingyunchi.job.service.StudentService;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/mybatis/students")
public class StudentController {
    private final StudentService studentService;

    public StudentController(StudentService studentService) {
        this.studentService = studentService;
    }

    @PostMapping
    public String save(@RequestBody Student student) {
        try {
            Student savedStudent = studentService.save(student);
            return "学生添加成功，id为：" + savedStudent.getId();
        } catch (Exception e) {
            return "学生添加失败，原因：" + e.getMessage();
        }
    }

    @GetMapping("/{id}")
    public Student findById(@PathVariable Long id) {
        return studentService.findById(id);
    }

    @GetMapping
    public List<Student> findAll() {
        return studentService.findAll();
    }

    @PutMapping
    public String update(@RequestBody Student student) {
        try {
            studentService.update(student);
            return "学生信息修改成功";
        } catch (Exception e) {
            return "学生信息修改失败，原因：" + e.getMessage();
        }
    }

    @DeleteMapping("/{id}")
    public String delete(@PathVariable Long id) {
        try {
            studentService.delete(id);
            return "学生删除成功";
        } catch (Exception e) {
            return "学生删除失败，原因：" + e.getMessage();
        }
    }
}